package com.qst.controller;

import com.qst.beans.Cart;
import com.qst.beans.CartItem;
import com.qst.beans.Product;
import com.qst.beans.User;
import com.qst.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class CartController {
    @Autowired
    ProductServiceImpl productService;

    @RequestMapping("/saveCart")
    public String addItemCart(Integer pid, Integer count, HttpSession session){
        Product pro = productService.findById(pid);
        CartItem cartItem = new CartItem();
        cartItem.setProduct(pro);
        cartItem.setCount(count);
//        cartItem.setSubtotal();
        //将购物项加入购物车
        Cart cart = getCart(session);
        cart.addItemCart(cartItem);
        System.out.println("购物车的商品项:");
        for (CartItem ci:cart.getCartItems()
             ) {
            System.out.println(ci.toString());
        }
//        System.out.println(cart.getTotal());
//        session.setAttribute("sessionCart",cart);
//        System.out.println("商品总额:"+((Cart)session.getAttribute("sessionCart")).getTotal());
        return "views/cart";
    }

    /*从session作用域中的到购物车,
    如果不存在，则创建
    * */
    private Cart getCart(HttpSession session){

        Cart sessionCart = (Cart) session.getAttribute("sessionCart");
        if (sessionCart == null){
            System.out.println("购物车不存在，创建.");
            sessionCart = new Cart();
            session.setAttribute("sessionCart",sessionCart);
        }
        return sessionCart;
    }

    @RequestMapping("/clearCart")
    public String clearCart(HttpSession session){
        Cart cart = getCart(session);
        cart.clearCart();
        return "views/cart";
    }

    @RequestMapping("/deleteCartItme")
    public String deleteCartItem(Integer pid,HttpSession session){
        Cart cart = getCart(session);
        cart.removeItemCart(pid);
        return "views/cart";
    }

//    我的购物车
    @RequestMapping("/myCart")
    public String myCart(HttpSession session){
        User enterUser = (User)session.getAttribute("enterUser");
        if (enterUser == null){
            System.out.println("未登录");
            return "views/login";
        }
        return "views/cart";
    }


}
